package com.hnust.controller.student;

import com.hnust.domain.Result;
import com.hnust.domain.Visual1;
import com.hnust.domain.Visual2;
import com.hnust.fx.FXMLController;
import com.hnust.service.StudentService;
import com.hnust.store.DataStore;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.Initializable;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.*;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import org.springframework.beans.factory.annotation.Autowired;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ResourceBundle;

@FXMLController
public class OverallDataController implements Initializable {


    public AnchorPane overAllDataWindow;
    public HBox studentAccuracy;
    public FlowPane classSubjectCount;
    public AnchorPane classSubjectContainer;
    public VBox classSubjectLabel;
    public HBox classSubjectBorder;

    @Autowired
    private StudentService studentService;
    @Autowired
    private DataStore dataStore;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        overAllDataWindow.parentProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                initPieChartAccuracy();
                initBarChartSubjectCount();
            }else{
                studentAccuracy.getChildren().clear();
                classSubjectCount.getChildren().clear();
            }
        });
    }

    public void initPieChartAccuracy(){

        //假数据生成
//        List<Visual2> visual2s=new ArrayList<>();
//        Visual2 d1=new Visual2(200,793,"线性代数");
//        Visual2 d2=new Visual2(330,793,"数字系统");
//        visual2s.add(d1);visual2s.add(d2);

        studentService.getVisual2(new Callback<Result<List<Visual2>>>() {
            @Override
            public void onResponse(Call<Result<List<Visual2>>> call, Response<Result<List<Visual2>>> response) {
                Result<List<Visual2>> result= response.body();
                assert result != null;
                List<Visual2> visual2s= result.getData();
                System.out.println(visual2s);
                //System.out.println(result);
                Platform.runLater(() -> {
                    if(result.getCode()==1){
                        //数据处理显示
                        for(Visual2 visual2:visual2s){
                            PieChart.Data data1=new PieChart.Data("错误率",visual2.getFalseTotal()==0?0.1:visual2.getFalseTotal());
                            PieChart.Data data2=new PieChart.Data("正确率",visual2.getRightTotal()==0?0.1:visual2.getRightTotal());
                            ObservableList<PieChart.Data> datalist= FXCollections.observableArrayList();
                            datalist.addAll(data1,data2);

                            PieChart pieChart=new PieChart(datalist);
                            pieChart.setTitle(visual2.getCourseName());
                            pieChart.setLabelsVisible(false);//设置标签可见性
                            //            pieChart.setLegendVisible(true);//设置显示可见性
                            //            pieChart.setLegendSide(Side.RIGHT);//设置显示可见性
                            //            pieChart.setLabelLineLength(10);//设置线长
                            //            pieChart.setAnimated(true);//设置动画数据变换
                            //            pieChart.setStartAngle(90);//设置旋转角度
                            //            pieChart.setTitleSide(Side.RIGHT);//设置标题位置
                            pieChart.getData().forEach(data -> {
                                Node node=data.getNode();
                                Tooltip tooltip=new Tooltip(data.getPieValue()==0.1?"做了0道题":"做了"+(int)data.getPieValue()+"道题");
                                tooltip.setFont(new Font(15));
                                Tooltip.install(node,tooltip);
                            });
                            studentAccuracy.getChildren().add(pieChart);
                        }
                    }else{
                        HBox hBox=new HBox();
                        Label l=new Label("暂无学生做题数据");
                        hBox.getChildren().add(l);
                        studentAccuracy.getChildren().add(hBox);
                    }
                });
            }
            @Override
            public void onFailure(Call<Result<List<Visual2>>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                    alert.showAndWait();
                });
            }
        },dataStore.getToken(),dataStore.getTeacher_id());
    }

    public void initBarChartSubjectCount(){
//                     <BarChart style="-fx-font-family: SimSun-ExtB;-fx-font-size: 13"
//                              fx:id="charBar" prefHeight="320">
//                        <xAxis>
//<!--                            Result<List<CourseData>> label="班级" side="LEFT" startMargin="200" endMargin="200"-->
//                            <CategoryAxis side="BOTTOM" />
//                        </xAxis>
//                        <yAxis>
//                            <NumberAxis upperBound="1000"  tickUnit="1" label="做题总数"/>
//                        </yAxis>
//                    </BarChart>

        studentService.getVisual1(new Callback<Result<List<Visual1>>>() {
            @Override
            public void onResponse(Call<Result<List<Visual1>>> call, Response<Result<List<Visual1>>> response) {
                Platform.runLater(() -> {
                    Result<List<Visual1>> result= response.body();
                    assert result != null;
                    List<Visual1> visual1s=result.getData();
                    //System.out.println(visual1s);
                    //System.out.println(result);
                    if(result.getCode()==1){

                        CategoryAxis x=new CategoryAxis();
                        x.setLabel("班级");x.setStartMargin(100);
                        x.setEndMargin(100);x.setSide(Side.LEFT);

                        NumberAxis y=new NumberAxis();
                        y.setLabel("做题总数");y.setTickUnit(5);
//                        y.setUpperBound(200);

                        LinkedHashSet<String> courseNames=new LinkedHashSet<>();
                        LinkedHashSet<String> classNames=new LinkedHashSet<>();
                        List<Visual1> visualNews=new ArrayList<>();
                        List<XYChart.Series<String,Number>> xys=new ArrayList<>();
                        //数据显示
                        for(Visual1 visual1:visual1s){
                            courseNames.add(visual1.getCourseName());
                            classNames.add(visual1.getClassName());
                        }
                        for(String course:courseNames){
                            for(String className:classNames){
                                int tmpSubjectCount=0;
                                for(Visual1 i:visual1s){
                                    if(i.getCourseName().equals(course)&&i.getClassName().equals(className)){
                                        tmpSubjectCount=i.getSubjectCount();
                                        break;
                                    }
                                }
                                visualNews.add(new Visual1(className,course,tmpSubjectCount));
                            }
                        }

                        for(String courseName:courseNames){
                            XYChart.Series<String,Number> xy=new XYChart.Series<>();
                            xy.setName(courseName);
                            xys.add(xy);
                        }
                        for(Visual1 visual1:visualNews){
                            for(XYChart.Series<String,Number> series:xys){
                                if(series.getName().equals(visual1.getCourseName())){
                                    series.getData().add(
                                            new XYChart.Data<>(visual1.getClassName(), visual1.getSubjectCount() == 0 ? 0.1 : visual1.getSubjectCount())
                                    );
                                }
                            }
                        }
                        BarChart<String,Number> barChart=new BarChart<String,Number>(x,y);
                        barChart.setPrefHeight(400);
                        //barChart.setPrefSize(1000,400);
                        barChart.getData().addAll(xys);
                        classSubjectCount.getChildren().add(barChart);
                        barChart.prefWidthProperty().bind(classSubjectCount.widthProperty());
                    }else{
                        HBox hBox=new HBox();
                        Label l=new Label("暂无学生做题数据");
                        hBox.getChildren().add(l);
                        classSubjectCount.getChildren().add(hBox);
                    }
                });
            }

            @Override
            public void onFailure(Call<Result<List<Visual1>>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                    alert.showAndWait();
                });
            }
        },dataStore.getToken(),dataStore.getTeacher_id());

    }
}
